<template>
  <ContentWrap>
    <div class="content">
      <div class="content_head flex-s">
        <div class="line"></div>
        <div class="title">基础信息</div>
      </div>
      <el-form 
        ref="formRef" 
        :inline="true" 
        :model="formData.data" 
        :rules="formRules" 
        class="-mb-15px"
        label-width="auto"
      >
      <el-form-item label="联系电话" prop="phone">
        <div class="flex-s">
          <el-input v-model="formData.data.phone" :maxLength="11" class="!w-230px mr-10px" clearable placeholder="请输入联系电话" @change="phoneChange"/>
          <el-button type="primary" @click="searchPhone(formData.data.phone)">查询账号</el-button>
        </div>
      </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.data.name" disabled class="!w-280px" clearable placeholder="请查询后带入姓名"/>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-tree-select
            v-model="formData.data.departmentId"
            class="!w-280px"
            :data="deptTree"
            clearable
            disabled
            :props="defaultProps"
            check-strictly
            default-expand-all
            placeholder="请查询后带入所属部门"
            value-key="deptId"
          />
        </el-form-item>
        <el-form-item label="岗位" prop="positionIds">
          <el-select v-model="formData.data.positionIds" multiple class="!w-280px" disabled placeholder="">
            <el-option
              v-for="item in postList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <!-- <el-input v-model="formData.data.positionIds" disabled class="!w-280px" clearable placeholder="请查询后带入岗位"/> -->
        </el-form-item>
        
      </el-form>
    </div>
  </ContentWrap>
  <ContentWrap class="flex-c">
    <el-button class="!w-80px" type="primary" :loading="loading" @click="submitForm">确定</el-button>
    <el-button class="!w-80px" type="warning" @click="closeForm">取消</el-button>
  </ContentWrap>


  <!-- 添加或修改用户对话框 -->
  <UserForm ref="UserFormRef" @success="userFormChange" />
</template>
<script setup>
  import {ref, reactive, inject} from "vue"
  import * as PersonnelApi from '@/api/system/personnel'
  import { defaultProps, handleTree } from '@/utils/tree'
  import { formRules } from './formRules'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { isPhoneNumber } from '@/utils/index'
  import * as PostApi from '@/api/system/post'
  import UserForm from './userForm.vue'
  let setPageStatus = inject('setPageStatus', () => {});
  const deptTree = inject('deptTree')
  const formRef = ref(null)
  const UserFormRef = ref(null)
  const message = useMessage() // 消息弹窗
  const router = useRouter()
  const postList = ref([]) // 岗位列表
  const formData = reactive({
    data: {
      name: '',
      phone: '',
      departmentId: '',
      positionIds: '',
      userType: 2,
    }
  })
  let loading = ref(false)
  let pageStatus = ref(1) // 1新增  2编辑
  /** 初始化 **/
  const init = async (type, id) => {
    pageStatus.value = type
    if (id) {
      getDetails(id)
    }else{
      formData.data = {
            name: '',
            phone: '',
            departmentId: '',
            positionIds: '',
            userType: 2,
      }
    }
    postList.value = await PostApi.getSimplePostList()
  }

  /** 查询详情信息 */
  const getDetails = async (id) => {
    loading.value = true
    try {
      const data = await PersonnelApi.getPersonnelDetail(id)

      console.log(data, '获取详情数据');
      formData.data = data

    } finally {
      loading.value = false
    }
  }


  /** 联系电话输入框失去焦点时触发 */
  const phoneChange = (val) => {
    if(!val){
      formRef.value.resetFields()
    }
  }
  const searchPhone = async (phone) => {
    if (!phone) {
      message.error('请输入联系电话')
      return
    }
    if (!isPhoneNumber(phone)) {
      message.error('请输入正确的手机号码')
      return
    }


    try {
      const data = await PersonnelApi.getPersonnelByPhone(phone)
      if(data){
        formData.data.adminUserId = data.id
        formData.data.name = data.username
        formData.data.departmentId = data.deptId
        formData.data.positionIds = data.postIds
        message.success(`查询成功，账号：${data.mobile}`)
      }else{
        message.confirm('未查询到相关信息，请先创建账号').then(() => {
          UserFormRef.value.open('create', phone)
        })
      }
    } catch (err) {
      console.log(err, '手机号查询人员失败原因');
    }
  }


  const userFormChange = (val) => {
    const {id, username, mobile, deptId, postIds} = val
    formData.data.adminUserId = id
    formData.data.name = username
    formData.data.phone = mobile
    formData.data.departmentId = deptId
    formData.data.positionIds = postIds
    submitForm()
  }


  const submitForm = async () => {
    const formEl = formRef.value
    if (!formEl) return
    let status = true
    formEl.validate((valid) => status = valid)
    setTimeout(()=> {
      if (!status) return

      if (pageStatus.value === 1) {
        PersonnelApi.addPersonnel(formData.data).then(res => {
          setPageStatus(1)
          message.success('新增成功')
        })
      } else {
        PersonnelApi.editPersonnel(formData.data).then(res => {
          setPageStatus(1)
          message.success('编辑成功')
        })
      }
    },10)

  }

  const closeForm = () => {
    // 关闭表单弹窗逻辑
    setPageStatus(1)
  }
  defineExpose({
    init,
  })
</script>
<style lang="scss" scoped>
.content{
    width: 100%;
    min-height: 80px;
    padding: 6px;
    // border-right: 1px solid #eee;
    box-sizing: border-box;
    .content_head {
        margin-bottom: 24px;
        .line {
            width: 5px;
            height: 21px;
            background: #50B5FF;
        }
        .title {
            font-size: 18px;
            color: #333;
            margin-left: 12px;
            font-weight: 600;
        }
    }
}
</style>
